<template>
  <div>
    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe @selection-change="handleSelectionChange" :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" width="55" align="center">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="weakCourseId" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column prop="studentName" label="学生姓名"></el-table-column>
        <el-table-column prop="courseName" label="课程名称"></el-table-column>
        <el-table-column prop="score" label="成绩"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="del(scope.row.weakCourseId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="学生课程" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="学生成绩ID" prop="scoreId">
          <el-input v-model="form.scoreId" placeholder="学生成绩ID"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "WeakCourse",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,      // 数据总数
      fromVisible: false,  // 弹窗显示状态
      form: {},  // 表单数据
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),  // 用户数据
      rules: {},  // 校验规则
      ids: []  // 存储选中的ID
    };
  },
  created() {
    this.load(1);  // 初始化加载第一页数据
  },
  methods: {
    // 打开新增弹窗
    handleAdd() {
      this.form = {};  // 新增时清空表单
      this.fromVisible = true;  // 打开弹窗
    },
    // 打开编辑弹窗
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));  // 深拷贝数据
      this.fromVisible = true;  // 打开弹窗
    },
    // 保存操作（新增或修改）
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.weakCourseId ? '/weak-courses/update' : '/weak-courses/add',
            method: this.form.weakCourseId ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 保存成功
              this.$message.success('保存成功');
              this.load(1);  // 重新加载数据
              this.fromVisible = false;  // 关闭弹窗
            } else {
              this.$message.error(res.msg);  // 显示错误信息
            }
          });
        }
      });
    },
    // 单个删除
    del(weakCourseId) {
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.delete('/weak-courses/delete/' + weakCourseId).then(res => {
          if (res.code === '200') {  // 删除成功
            this.$message.success('删除成功');
            this.load(1);  // 重新加载数据
          } else {
            this.$message.error(res.msg);  // 显示错误信息
          }
        });
      }).catch(() => {
        // 取消删除
      });
    },
    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据');
        return;
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.delete('/weak-courses/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {  // 批量删除成功
            this.$message.success('操作成功');
            this.load(1);  // 重新加载数据
          } else {
            this.$message.error(res.msg);  // 显示错误信息
          }
        });
      }).catch(() => {
        // 取消批量删除
      });
    },
    // 处理选中的数据
    handleSelectionChange(val) {
      this.ids = val.map(v => v.weakCourseId);  // 存储选中的ID
    },
    // 分页加载数据
    load(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      this.$request.get('/weak-courses/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }).then(res => {
        this.tableData = res.data.records;  // 填充表格数据
        this.total = res.data.total;  // 总数据条数
      });
    },
    // 分页切换
    handleCurrentChange(pageNum) {
      this.load(pageNum);  // 重新加载数据
    }
  }
};
</script>

<style scoped>
/* Add your styles here */
</style>
